package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.common.SessionConst;
import com.itheima.health.pojo.dto.SubmitDTO;
import com.itheima.health.pojo.entity.Member;
import com.itheima.health.pojo.entity.Order;
import com.itheima.health.pojo.entity.Setmeal;
import com.itheima.health.pojo.result.Result;
import com.itheima.health.pojo.vo.OrderFindByIdVO;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.SetMealService;
import com.itheima.health.utils.AliMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;

import java.text.SimpleDateFormat;
import java.util.List;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController

@RequestMapping("/mobile")
@Slf4j
public class MobileController {


    @Autowired
    private AliMessageUtil aliMessageUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SetMealService setMealService;

    @Autowired
    private MemberService memberService;




    /**
     * 预约订单提交
     * @param
     * @return
     */
    @PostMapping("/order/submit")
    public Result submit(@RequestBody SubmitDTO submitDTO) throws ParseException {
        Order order = orderService.submit(submitDTO);
        return new Result(true, MessageConst.ORDER_SUCCESS, order);
    }



    /**
     * 手机端体检预约_套餐展示
     * @param
     * @return
     */
    @GetMapping("/setmeal/getSetmeal")
    public Result getSetmeal() {
        List<Setmeal> setmeal = setMealService.getSetmeal();
        return new Result(true, MessageConst.QUERY_SETMEAL_SUCCESS ,setmeal);
    }

    /**
     * 体检预约
     * 套餐详情
     * @param id
     * @return
     */
    @GetMapping("/setmeal/findById")
    public Result findById(Integer id) {
        Setmeal setmeal = setMealService.findById(id);
        return new Result(true, MessageConst.QUERY_SETMEAL_SUCCESS, setmeal);
    }


//    @PostMapping("/validateCode/send")
//    public Result sendValidateCode(String type, String telephone){
//        orderService.sendValidateCode(type, telephone);
//        return new Result(true, MessageConst.SEND_VALIDATECODE_SUCCESS);
//    }

    /**
     * 发送验证码
     * @param type
     * @param telephone
     * @return
     */
    @PostMapping("/validateCode/send")
    public Result sendValidateCode(String type, String telephone) {
        log.info("发送验证码类型:{}，手机号，：{}",type,telephone);

        //封装6位随机数作为短信验证码
        Random random = new Random();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int append = random.nextInt(10);
            builder.append(append);
        }
        log.info("验证码：{}",builder.toString());

        try {
            //调用aliyun服务发送短信
            aliMessageUtil.sentMessage(telephone,builder.toString());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //设置5分钟过期 并且分类型存储在redis中
        if (type.equals("MOBILE_SIGNIN")) {
            log.info("存储验证码到：{}", RedisConst.MOBILE_SIGNIN);
            redisTemplate.opsForValue().set(RedisConst.MOBILE_SIGNIN+telephone, builder.toString(), Duration.ofMinutes(5));
        }else if (type.equals("ORDER")){
            log.info("存储验证码到：{}",RedisConst.ORDER);
            redisTemplate.opsForValue().set(RedisConst.ORDER +telephone, builder.toString(), Duration.ofMinutes(5));
        }else throw new RuntimeException("验证码类型错误");
        return new Result(true,MessageConst.SEND_VALIDATECODE_SUCCESS);
    }

    /**
     * 验证码登录
     * @param map
     * @return
     */
    @PostMapping("/login/smsLogin")
    public Result smsLogin(@RequestBody HashMap map, HttpServletRequest request) {
        log.info("手机号：{}，验证码：{}",map.get("telephone"),map.get("validateCode"));

        //送redis缓存中查找是否有指定的验证码
        String code = (String) redisTemplate.opsForValue().get(RedisConst.MOBILE_SIGNIN+map.get("telephone"));
        if (code == null || !code.equals(map.get("validateCode"))) {
            return new Result(false,"验证码错误");
        }
        //有则通过，并删除缓存中的验证码（验证码只能使用一次）
        redisTemplate.delete(RedisConst.MOBILE_SIGNIN+map.get("telephone"));

        //注入一个默认用户，避免被登录拦截
        request.getSession().setAttribute(SessionConst.SESSION_USERNAME,new Member());
        //数据库中查找用户
//        Member member=memberDao.getByTelephone((String) map.get("telephone"));


        return new Result(true,"验证码正确");
    }


    /**
     * 订单数据展示
     * @param id
     * @return
     */
    @GetMapping("/order/findById")
    public Result findById(String id) throws Exception {
        log.info("订单数据展示:{}", id);
        OrderFindByIdVO vo = orderService.findById(id);
        return new Result(true, MessageConst.QUERY_ORDER_SUCCESS,vo);
    }
}
